<template>
  <div class="form-wapper">
    <van-nav-bar
      :title="$route.meta.title"
      left-arrow
      :border="false"
      @click-left="clickLeft"
      @click-right="clickSubmit"
    >
      <template #right>
        <van-icon name="success" size="24" />
        <span
          style="
            margin-left: 2px;
            color: #fff;
            margin-top: 3px;
            font-size: 20px;
          "
          >保存</span
        >
      </template>
    </van-nav-bar>
    <van-form @submit="onSubmit" scroll-to-error class="applyContent">
      <van-row type="flex">
        <van-col span="12" class="scanClick"
          ><van-field
            v-model="companyType"
            name="companyType"
            label="产品来源"
            required
            input-align="center"
            v-show="companyTypeList.length > 1"
          >
            <template #input>
              <van-radio-group v-model="companyType" direction="horizontal">
                <van-radio
                  v-for="item in companyTypeList"
                  :key="item.name"
                  :name="item.name"
                  >{{ item.text }}</van-radio
                >
              </van-radio-group>
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field v-model="applyDate" name="applyDate" label="请验日期">
            <template #input>
              <picker-date-one v-model="applyDate" />
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="section"
            name="section"
            label="申请单位"
            required
            input-align="center"
            :rules="[{ required: true, message: '请选择申请单位' }]"
          >
            <template #input>
              <department-tree v-model="section" />
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="materialType"
            name="materialType"
            label="物料类型"
            required
            input-align="center"
            :rules="[{ required: true, message: '请选择物料类型' }]"
          >
            <template #input>
              <material-type
                v-model="materialType"
                :materialTypeName="materialTypeName"
              />
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="materialCode"
            name="materialCode"
            label="物料名称"
            required
            input-align="center"
            :rules="[{ required: true, message: '请选择物料' }]"
          >
            <template #input>
              <material-name
                :materialType="materialType"
                :materialName="materialName"
                @change="getMaterialInfo"
              />
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="batchID"
            name="batchID"
            label="批号"
            required
            input-align="center"
            placeholder="请填写"
            :rules="[{ required: true, message: '请输入批号' }]"
          >
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="productSpecification"
            name="productSpecification"
            label="规格"
            required
            clickable
            input-align="center"
            :rules="[{ required: true, message: '请输入规格' }]"
          >
            <template #input>
              <specification v-model="productSpecification" />
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="packStandard"
            name="packStandard"
            label="包装规格"
            input-align="center"
          >
          </van-field>
        </van-col>
        <van-col span="12" v-if="companyType == 'Company'">
          <van-field
            v-model="companyCode"
            name="companyCode"
            label="供应商"
            clickable
            input-align="center"
          >
            <template #input>
              <company-com v-model="companyCode" :materialCode="materialCode" />
            </template>
          </van-field>
        </van-col>
        <van-col span="12" v-if="companyType == 'Company'">
          <van-field
            v-model="factoryBatchID"
            name="factoryBatchID"
            label="供应商批号"
            input-align="center"
            placeholder="请填写"
          >
          </van-field>
        </van-col>
        <!-- <van-col span="12" v-if="companyType == 'Company'">
          <van-field
            v-model="producerCode"
            name="producerCode"
            label="生产商"
            clickable
            required
            input-align="center"
            :rules="[{ required: true, message: '请选择生产商' }]"
          >
            <template #input>
              <company-com
                v-model="producerCode"
                :materialCode="materialCode"
              />
            </template>
          </van-field>
        </van-col> -->
        <van-col span="12" v-if="companyType == 'Dept'">
          <van-field
            v-model="companyCode"
            name="companyCode"
            label="生产车间"
            required
            input-align="center"
            :rules="[{ required: true, message: '请选择生产车间' }]"
          >
            <template #input>
              <department-tree v-model="companyCode" />
            </template>
          </van-field>
        </van-col>

        <van-col span="8">
          <van-field
            v-model="total"
            name="total"
            label="数量/单位"
            required
            placeholder="请输入"
            input-align="center"
            :rules="[{ required: true, message: '请输入数量' }]"
          >
          </van-field>
        </van-col>
        <van-col span="4">
          <van-field
            v-model="unitCode"
            name="unitCode"
            placeholder="请选择"
            v-if="unitShow"
          >
            <template #input>
              <picker-unit v-model="unitCode" />
            </template>
          </van-field>
        </van-col>

        <van-col span="12">
          <van-field
            v-model="standard"
            name="standard"
            label="件数"
            placeholder="请输入"
            input-align="center"
          >
          </van-field>
        </van-col>
        <!-- <van-col span="4">
          <van-field
            v-model="standardUnitCode"
            name="standardUnitCode"
            placeholder="请选择"
          >
            <template #input>
              <picker-unit v-model="standardUnitCode" />
            </template>
          </van-field>
        </van-col> -->

        <!-- <van-col span="12">
          <van-field
            v-model="testStandard"
            name="testStandard"
            label="检验标准"
            required
            clickable
            input-align="center"
          >
            <template #input>
              <text-standard
                v-model="testStandard"
                :materialCode="materialCode"
              />
            </template>
          </van-field>
        </van-col> -->
        <van-col span="8">
          <van-field
            v-model="ProductDateType"
            name="ProductDateType"
            label="日期类型"
            input-align="center"
            required
          >
            <template #input>
              <fixed-select
                v-model="ProductDateType"
                :dataList="productDateTypeArr"
              />
            </template>
          </van-field>
        </van-col>
        <van-col span="4">
          <van-field v-model="productDate" name="productDate">
            <template #input>
              <picker-date-two v-model="productDate" />
            </template>
          </van-field>
        </van-col>
        <van-col span="8">
          <van-field
            v-model="EffectDateType"
            name="EffectDateType"
            label="到期类型"
            input-align="center"
            required
          >
            <template #input>
              <fixed-select
                v-model="EffectDateType"
                :dataList="effectDateTypeArr"
              />
            </template>
          </van-field>
        </van-col>
        <van-col span="4">
          <van-field v-model="effectDate" name="effectDate">
            <template #input>
              <picker-date-two v-model="effectDate" />
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="urgencyDegreeCode"
            name="urgencyDegreeCode"
            label="紧急程度"
            required
            clickable
            input-align="center"
            :rules="[{ required: true, message: '请选择紧急程度' }]"
          >
            <template #input>
              <urgency-degree v-model="urgencyDegreeCode" />
            </template>
          </van-field>
        </van-col>
        <van-col span="24">
          <van-field
            v-model="applyRemarks"
            name="applyRemarks"
            rows="1"
            label="备注"
            type="textarea"
            placeholder="请输入备注"
            input-align="left"
          >
          </van-field>
        </van-col>
      </van-row>
      <div style="display: none; justify-content: center">
        <van-button
          round
          block
          :disabled="committing"
          :loading="committing"
          native-type="submit"
          ref="submitBtn"
          >提交</van-button
        >
      </div>
    </van-form>
    <div class="scan" v-if="scanShow">
      <div id="bcid">
        <div style="height: 40%"></div>
        <p class="tip">...载入中...</p>
      </div>
      <footer>
        <button @click="closeModel">退出</button>
      </footer>
    </div>
  </div>
</template>

<script>
import {
  Form,
  Field,
  RadioGroup,
  Radio,
  Button,
  Popup,
  Toast,
  Col,
  Row,
  DropdownMenu,
  DropdownItem,
  Checkbox,
  CheckboxGroup,
  Notify,
  NavBar,
  Icon,
} from "vant";
import FixedSelect from "@/components/FixedSelect";
import DepartmentTree from "./DepartmentTree";
import PickerDate from "./PickerDate";
import MaterialType from "./MaterialType";
import MaterialName from "./MaterialName";
import Specification from "./Specification";
import CompanyCom from "./CompanyCom";
import PickerDateOne from "./PickerDateOne";
import PickerDateTwo from "./PickerDateTwo";
import PickerUnit from "./PickerUnit";
import TextStandard from "@/components/TextStandard";
import UrgencyDegree from "./UrgencyDegree";
import AreaTree from "./AreaTree";
import SamplePoint from "./SamplePoint";

import {
  getTestStandardAttributeSelect,
  getCheckApplyBatchID,
  getWorkflowPassword,
  addApply,
  GetMateriaLeffectivedateByCodeStandard,
} from "@/api/check";
import { to } from "@/utils";
let scan = null;
export default {
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    [Col.name]: Col,
    [Row.name]: Row,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Notify.name]: Notify,
    [NavBar.name]: NavBar,
    [Icon.name]: Icon,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    DepartmentTree,
    PickerDate,
    MaterialType,
    MaterialName,
    Specification,
    CompanyCom,
    PickerUnit,
    TextStandard,
    UrgencyDegree,
    PickerDateOne,
    AreaTree,
    SamplePoint,
    FixedSelect,
    PickerDateTwo,
  },
  props: {
    applySource: {
      type: String,
    },
  },
  data() {
    return {
      token: "",
      companyCode: "",
      companyTypeList: [
        {
          name: "Dept",
          text: "自制",
        },
        {
          name: "Company",
          text: "外购",
        },
      ],
      applyDate: "",
      section: "",
      sectionUserID: "",
      materialType: "",
      materialTypeName: "",
      materialCode: "",
      materialName: "",
      batchID: "",
      productSpecification: "",
      packStandard: "",
      Company: "",
      factoryBatchID: "",
      producerName: "",
      companyType: "Dept",
      total: "",
      unitCode: "",
      standard: "",
      standardUnitCode: "",
      productDate: "",
      effectDate: "",
      testStandard: "",
      urgencyDegreeCode: "",
      committing: false,
      applyRemarks: "",
      checkPwd: {
        show: false,
        userid: null,
        username: null,
      },
      values: null,
      refreshItem: true,
      chooseArr: [],
      itemArr: [],
      producerCode: "",
      selectArr: [],
      samplePointAttribute: "",
      samplePointAttributeName: "",
      sampleSite: "",
      sampleSiteName: "",
      state: "",
      scanShow: false,
      unitShow: true,
      scanObj: {},
      productDateTypeArr: [
        { value: "1", text: "生产日期" },
        { value: "2", text: "采收(加工)日期" },
      ],
      effectDateTypeArr: [
        { value: "1", text: "有效期" },
        { value: "2", text: "贮存日期" },
      ],
      EffectDateType: "",
      ProductDateType: "",
    };
  },
  watch: {
    productDate(val) {
      if (val && val != "Invalid Date") {
        if (this.ProductDateType == "1" && this.EffectDateType == "1") {
          let date = new Date(val);
          date.setDate(0); // 设置为上个月的最后一天
          date.setFullYear(date.getFullYear() + 3); // 加上三年
          var computeDate = date.toISOString().split("T")[0]; // 返回YYYY-MM-DD格式的字符串
          this.effectDate = computeDate;
        }
      }
    },
    companyType(val) {
      if (val) {
        this.unitShow = false;
        this.unitShow = true;
      }
    },
  },
  methods: {
    clickLeft() {
      if (scan && scan != "") {
        scan.close();
      }
      this.$router.replace({ name: "ApplyList" });
    },
    clickSubmit() {
      this.$refs.submitBtn.click();
    },
    async onSubmit(values) {
      if (
        this.productDate == "Invalid Date" ||
        this.effectDate == "Invalid Date"
      ) {
        Notify({ type: "danger", message: "日期不能为空" });
        return false;
      }

      var q = {
        Token: this.token,
        Search: [values.materialCode, values.batchID, "ProcessMaterial"],
      };
      const [err, res] = await to(getCheckApplyBatchID(q));
      const pageModel = {
        Token: this.token,
        Search: [values.materialCode, "10"],
      };
      getWorkflowPassword({ pageModel }).then(({ Result }) => {
        const { state, isPassword, userId, userName } = Result;
        this.state = state;
        if (isPassword) {
          this.checkPwd.userid = userId;
          this.checkPwd.username = userName;
          this.values = Object.assign({}, values);
          this.checkPwd.show = true;
        } else {
          this.success(Object.assign({}, values));
        }
      });
    },
    checkAll() {
      this.$refs.checkboxGroup.toggleAll(true);
    },
    toggleAll() {
      this.$refs.checkboxGroup.toggleAll();
    },
    getMaterialInfo(val) {
      this.materialCode = val.value;
      this.packStandard = val.packStandard;
    },
    getCheckItemInfo(val) {
      this.chooseArr = [];
      var result = { queryModel: { Token: this.token, code: val } };
      getTestStandardAttributeSelect(result)
        .then((response) => {
          var res = response.Result;
          for (var i = 0; i < res.length; i++) {
            this.chooseArr.push(res[i].value);
          }
          this.itemArr = res;
        })
        .catch(() => {});
    },
    success(values) {
      var that = this;
      // if (this.chooseArr.length == 0) {
      //   Notify({ type: "danger", message: "检验项目不能为空" });
      //   return false;
      // }
      // this.selectArr = [];
      // this.chooseArr.map((item) => {
      //   that.itemArr.map((item1) => {
      //     if (item == item1.value) {
      //       that.selectArr.push(item1);
      //     }
      //   });
      // });
      values || (values = this.values);
      this.committing = true;
      //values["attributes"] = that.selectArr;
      values.Token = this.token;
      values.state = this.state;
      addApply(values)
        .then(() => {
          this.refreshItem = false;
          this.committing = false;
          this.section = "";
          this.batchID = "";
          this.productSpecification = "";
          this.factoryBatchID = "";
          this.total = "";
          this.standard = "";
          this.applyRemarks = "";
          that.selectArr = [];
          window.scroll(0, 0);
          this.$nextTick(() => {
            this.refreshItem = true;
          });
          that.$router.replace({ name: "ApplyList" });
        })
        .catch(() => {
          this.committing = false;
        });
    },
    DateAdd(interval, number, date) {
      /*
       *   功能:实现JSScript的DateAdd功能.
       *   参数:interval,字符串表达式，表示要添加的时间间隔.
       *   参数:number,数值表达式，表示要添加的时间间隔的个数.
       *   参数:date,时间对象.
       *   返回:新的时间对象.
       *   var   now   =   new   Date();
       *   var   newDate   =   DateAdd( "d ",5,now);
       *---------------   DateAdd(interval,number,date)   -----------------
       */
      switch (interval) {
        case "y ": {
          date.setFullYear(date.getFullYear() + number);
          return date;
          break;
        }
        case "q ": {
          date.setMonth(date.getMonth() + number * 3);
          return date;
          break;
        }
        case "m ": {
          date.setMonth(date.getMonth() + number);
          return date;
          break;
        }
        case "w ": {
          date.setDate(date.getDate() + number * 7);
          return date;
          break;
        }
        case "d ": {
          date.setDate(date.getDate() + number);
          return date;
          break;
        }
        case "h ": {
          date.setHours(date.getHours() + number);
          return date;
          break;
        }
        case "m ": {
          date.setMinutes(date.getMinutes() + number);
          return date;
          break;
        }
        case "s ": {
          date.setSeconds(date.getSeconds() + number);
          return date;
          break;
        }
        default: {
          date.setDate(date.getDate() + number);
          return date;
          break;
        }
      }
    },
    getTimeFormat(dataFormat, newData) {
      var newTime = "";
      var nowTime = newData;
      nowTime.setTime(nowTime.getTime());
      var year = nowTime.getFullYear();
      var month =
        nowTime.getMonth() + 1 < 10
          ? "0" + (nowTime.getMonth() + 1)
          : nowTime.getMonth() + 1;
      var date =
        nowTime.getDate() < 10 ? "0" + nowTime.getDate() : nowTime.getDate();
      var hours =
        nowTime.getHours() < 10 ? "0" + nowTime.getHours() : nowTime.getHours();
      var minutes =
        nowTime.getMinutes() < 10
          ? "0" + nowTime.getMinutes()
          : nowTime.getMinutes();
      if (dataFormat == "yyyy.MM.dd") {
        newTime = year + "." + month + "." + date;
      } else if (dataFormat == "yyyy-MM-dd") {
        newTime = year + "-" + month + "-" + date;
      } else if (dataFormat == "yyyy/MM/dd") {
        newTime = year + "/" + month + "/" + date;
      } else if (dataFormat == "yyyy.MM.dd HH:mm") {
        newTime = year + "." + month + "." + date + " " + hours + ":" + minutes;
      } else if (dataFormat == "yyyy-MM-dd HH:mm") {
        newTime = year + "-" + month + "-" + date + " " + hours + ":" + minutes;
      } else if (dataFormat == "yyyy/MM/dd HH:mm") {
        newTime = year + "/" + month + "/" + date + " " + hours + ":" + minutes;
      } else if (dataFormat == "HH:mm") {
        newTime = hours + ":" + minutes;
      }
      return newTime;
    },
    GetMateriaLeffectivedateByCodeStandard() {
      var result = {
        Token: this.token,
        Code: this.materialCode,
        StandardVersion: this.testStandard,
      };
      if (!this.materialCode) {
        return false;
      }
      GetMateriaLeffectivedateByCodeStandard(result).then(({ Result }) => {
        if (Result.EffectiveNumber && Result.EffectiveNumber > 0) {
          var unit = "";
          if (Result.EffectiveUnit == "year") {
            unit = "y ";
          } else if (Result.EffectiveUnit == "month") {
            unit = "m ";
          } else if (Result.EffectiveUnit == "day") {
            unit = "d ";
          }
          var now = new Date(this.productDate);
          var newDate = this.DateAdd(unit, Result.EffectiveNumber, now);
          var newDate1 = this.DateAdd("d ", -1, newDate);
          this.effectDate = this.getTimeFormat("yyyy-MM-dd", newDate1);
        }
      });
    },
    openScan() {
      var that = this;
      this.scanShow = true;
      this.timer = setTimeout(that.startRecognize, 500);
    },
    startRecognize() {
      var that = this;
      this.timer = null;
      if (!window.plus) return;
      scan = new plus.barcode.Barcode("bcid");
      scan.onmarked = onmarked;
      scan.start();
      function onmarked(type, result, file) {
        switch (type) {
          case plus.barcode.QR:
            type = "QR";
            break;
          case plus.barcode.EAN13:
            type = "EAN13";
            break;
          case plus.barcode.EAN8:
            type = "EAN8";
            break;
          default:
            type = "其它" + type;
            break;
        }

        var scanObj = JSON.parse(result);
        scan.close();
        that.scanShow = false;
        that.materialType = scanObj.materialType;
        that.materialTypeName = scanObj.materialTypeName;
        that.materialName = scanObj.materialName;
        that.materialCode = scanObj.materialCode;
        that.batchID = scanObj.batchID;
        that.samplePointAttribute = scanObj.areaCode;
        that.samplePointAttributeName = scanObj.areaName;
        that.sampleSite = scanObj.attributeCode;
        that.sampleSiteName = scanObj.attributeName;

        //   if (that.materialType && that.materialType == result.materialType) {
        //     if (that.materialName && that.materialName == result.materialCode) {
        //       that.batch = result.batchID;
        //     } else {
        //       that.materialCode = result.materialCode;
        //     }
        //   } else {
        //     that.materialType = result.materialType;
        //   }
        // that.getScanType(JSON.parse(result).testID);
      }
    },
    closeModel() {
      this.scanShow = false;
      if (!window.plus) return;
      scan.close();
    },
  },
  async created() {
    this.token = localStorage.getItem("tokenKey");
  },
  mounted() {},
};
</script>

<style lang="less" scoped>
/deep/.van-nav-bar {
  height: 1rem;
}
/deep/.van-nav-bar__content {
  height: 1rem !important;
}
.van-form {
  height: calc(100% - 1rem);
  overflow-y: auto;
}
/deep/ .van-field__body {
  border: 1px solid #ddd;
}
.van-row {
  background: #fff;
}
.van-hairline-unset--top-bottom::after,
.van-hairline--top-bottom::after {
  border-width: 0;
}

.form-wapper {
  height: 100%;
  overflow: hidden;
}
/deep/.van-button--block {
  width: 90%;
  height: 36px;
}
.checkItem {
  width: 100%;
  padding: 0 10px;
  margin-top: 20px;
  box-sizing: border-box;
  font-size: 12px;
}
.checkItem > div {
  border: 1px solid #ccc;
}
.checkItem {
  width: 100%;
  padding: 0 10px;
  margin-top: 20px;
  box-sizing: border-box;
  font-size: 12px;
}
.checkItem > div {
  border: 1px solid #ccc;
}
.itemTit {
  height: 32px;
  background: #49bbef;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
  color: #fff;
}
.itemTit button {
  color: #000;
}
.itemContent {
  padding: 10px 10px 0 10px;
  width: 100%;
  box-sizing: border-box;
}
.checkItem .van-checkbox__icon .van-icon {
  width: 0.4rem !important;
  height: 0.4rem !important;
  line-height: 0.4rem !important;
}
.van-checkbox {
  width: 33%;
  margin-bottom: 10px;
}
.scan {
  height: 100%;
  width: 100%;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;

  #bcid {
    width: 100%;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 1rem;
    text-align: center;
    color: #fff;
    background: #ccc;
    font-size: 20px;
    z-index: 999;
    .closeModel {
      position: absolute;
      top: 20px;
      right: 20px;
    }
  }
  footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    bottom: 0;
    height: 1rem;
    font-size: 20px;
    button {
      height: 100%;
      width: 100%;
      border: none;
    }
  }
}
/deep/.van-cell {
  padding: 0.2rem 0.4rem;
}
/deep/.van-field__body {
  border-radius: 2px !important;
  border: 1px solid #ddd;
}
/deep/.van-cell {
  font-size: 0.32rem;
}
</style>